import OSS from 'ali-oss'

interface IBase64Info {
  dataURL: string
  type: string
}

export interface IOssModel {
  RequestId: string
  Credentials: {
    AccessKeySecret: string
    Expiration: string
    AccessKeyId: string
    SecurityToken: string
  }
  AssumedRoleUser: {
    AssumedRoleId: string
    Arn: string
  }
  EndPoint: string
  Bucket: string
  OssUrl: string
  path: string
}

async function browserUpload(filePath: string, ossInfo: IOssModel): Promise<string> {
  const client = new OSS({
    accessKeyId: ossInfo.Credentials.AccessKeyId,
    accessKeySecret: ossInfo.Credentials.AccessKeySecret,
    stsToken: ossInfo.Credentials.SecurityToken,
    bucket: ossInfo.Bucket,
    endpoint: ossInfo.EndPoint,
  })
  const aliyunFileKey = ossInfo.path + new Date().getTime() + '.jpg'
  let result: OSS.PutObjectResult
  if (filePath.startsWith('data:image/jpeg;base64')) {
    result = await client.put(
      aliyunFileKey,
      convertBase64UrlToBlob({
        dataURL: filePath,
        type: 'image/jpeg',
      }),
    )
  } else {
    result = await client.put(aliyunFileKey, await h5UrlToBlob(filePath))
  }
  return `${ossInfo.OssUrl}${result.name}`
  // return result.url;
}

function h5UrlToBlob(url: string) {
  return new Promise<any>((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.responseType = 'blob'
    xhr.onload = function (e) {
      if (this.status === 200) {
        const Blob = this.response
        // console.log(myBlob)
        resolve(Blob)
        // myBlob现在是对象URL指向的blob。
      }
    }
    xhr.send()
  })
}

function convertBase64UrlToBlob(base64: IBase64Info) {
  const urlData = base64.dataURL
  const type = base64.type
  let bytes = null
  if (urlData.split(',').length > 1) {
    // 是否带前缀
    bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte
  } else {
    bytes = window.atob(urlData)
  }
  // 处理异常,将ascii码小于0的转换为大于0
  const ab = new ArrayBuffer(bytes.length)
  const ia = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new Blob([ab], { type })
}

export default browserUpload
